from fastapi import FastAPI, HTTPException
import httpx

from entity.parameters import BusinessParametersGoods
from app.sql.mysql_goods import select_goods_list, select_goods_count, select_goods_spec_list, \
    select_goods_barcode_list, select_goods_brand_count, select_goods_brand_info
from app.utils.signUtil import sign_util

# from app.src.entity.goods_query import BusinessParametersGoods, CommonParameters
# from app.src.util.signUtil import sign_util

app = FastAPI()


# 当前位置： API文档 > 货品类
# vip_api_goods_query.php（查询平台货品）
async def call_external_api(query, item: BusinessParametersGoods):
        try:
            async with httpx.AsyncClient() as client:
                param = sign_util(item.start_time, item.end_time, item.page_no, item.page_size)
                str_len = 'https://api.wangdian.cn/openapi2/' + query
                # 发送 GET 请求，参数通过 params 传递
                response =  await client.get(
                    url=str_len,
                    params=param,
                    timeout=10  # 设置超时时间（秒）
                )
            # 检查响应状态码
            response.raise_for_status()  # 若状态码非 200，抛出异常
            return response.json()

        except httpx.HTTPStatusError as e:
            # 处理 HTTP 错误（如 404、500 等）
            return {
                "error": f"HTTP error occurred: {e.response.status_code}",
                "detail": e.response.text
            }
        except httpx.RequestError as e:
            # 处理请求错误（如超时、网络不可达等）
            return {
                "error": f"Request failed: {e}",
                "detail": str(e)
            }


async def call_goods_api(page_no:int, page_size:int, goodsName:str):
        """
        三层嵌套查询：
        1. 查询所有用户
        2. 对每个用户，查询其订单
        3. 对每个订单，查询其详情
        """
        try:
            # 步骤1：查询表A（用户表）所有数据
            goods_list = select_goods_list(page_no,page_size, goodsName)
            # 步骤2：遍历表A记录，查询表B（订单表）
            result_goods = []
            for good in goods_list:
                # 查询该用户的所有订单
                goods_spec_list = select_goods_spec_list(good["goods_id"])
                # 步骤3：遍历表B记录，查询表C（订单详情表）
                result_spec = []
                for goods_spec in goods_spec_list:
                    # 查询该订单的所有详情
                    good_barcode = select_goods_barcode_list(good["goods_id"],goods_spec["spec_id"])
                    goods_spec["barcode_list"] = good_barcode
                    result_spec.append(goods_spec)
                good["spec_list"] = goods_spec_list
                result_goods.append(good)
            return result_goods
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))


async def get_goods_count()->int:
    try:
        count = select_goods_count()
        return count
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def call_goods_brand()->dict:
    goods_spec_list = select_goods_brand_info()
    return goods_spec_list

async def get_goods_brand_count()->int:
    try:
        count = select_goods_brand_count()
        return count
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
